<template>
  <div v-loading="fullLoading">
    <!-- <div class="grid-content bg-purple-light" />
      <div class="dataTitle"><i class="el-icon-office-building" style="padding:20px" />数据字典</div>-->
    <div class="box-header box">
      <el-card>
        <el-page-header
          :title="$t('common.back')"
          :content="$t('modules.contract.add_contract')"
          style="margin-bottom: 20px"
          @back="back"
        />
        <!-- 合同详情 -->
        <div style="font-size: 18px; margin: 0px 0px 20px 10px">
          <span
            style="
              display: inline-block;
              height: 30px;
              border-left: 4px solid #2569c3;
              text-indent: 10px;
            "
            >{{ $t("modules.contract.basic") }}
          </span>
        </div>
        <el-form
          ref="contractData"
          :model="contractData"
          label-width="150px"
          :rules="rules"
        >
          <el-row class="flexContract">
            <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item
                :label="$t('common.customer_name')"
                class="item"
                prop="userName"
              >
                <el-input
                  ref="name"
                  v-model="contractData.userName"
                  clearable
                  style="width: 100%"
                  @focus="openCustomerList"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item
                class="item"
                :label="$t('modules.contract.contract_no')"
                style="width: 100%"
                prop="contractNum"
              >
                <el-input
                  v-model="contractData.contractNum"
                  maxlength="32"
                  show-word-limit
                  style="width: 80%"
                  :disabled="noContract"
                />
                <el-tooltip
                  style="width: 18%; margin-left: 10px"
                  effect="dark"
                  :content="$t('flycare.contract.no_contract_tip')"
                  placement="top"
                >
                  <el-checkbox v-model="noContract" @change="changeNoContract">{{
                    $t("flycare.contract.no_contract")
                  }}</el-checkbox>
                </el-tooltip>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="flexContract">
            <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item
                class="item"
                :label="$t('common.startDate')"
                prop="effectiveDate"
              >
                <el-date-picker
                  v-model="contractData.effectiveDate"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYYMMDD"
                  range-separator="-"
                  :start-placeholder="$t('common.start_time')"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item
                class="item"
                :label="$t('modules.contract.sign_entity_id')"
                prop="signEntityId"
                style="width: 100%"
              >
                <el-select
                  v-model="contractData.signEntityId"
                  clearable
                  style="width: 100%"
                  placeholder=""
                >
                  <el-option
                    v-for="item in signOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item prop="email">
            <template #label>
              <span>
                <div style="margin-bottom: -20px">
                  {{ $t("flycare.contract.fixed_notify_email") }}
                  <el-tooltip placement="top">
                    <template #content>
                      <div>
                        {{ $t("modules.contract.email_hint") }}
                      </div></template
                    >
                    <i class="el-icon-warning" style="font-size: 2px" />
                  </el-tooltip>
                </div> </span
            ></template>
            <!--            <el-input-->
            <!--              v-model="fixedEmail"-->
            <!--              style="display: inline-block"-->
            <!--              -->
            <!--              type="textarea"-->
            <!--              maxlength="1000"-->
            <!--              readonly-->
            <!--            />-->
            <label>{{ fixedEmail }}</label>
          </el-form-item>
          <el-form-item prop="email">
            <template #label>
              <span>
                <div style="margin-bottom: -20px">
                  {{ $t("modules.contract.email") }}
                  <el-tooltip placement="top">
                    <template #content>
                      <div>
                        {{ $t("modules.contract.email_hint") }}
                      </div></template
                    >
                    <i class="el-icon-warning" style="font-size: 2px" />
                  </el-tooltip>
                </div> </span
            ></template>
            <el-input
              v-model="contractData.email"
              style="display: inline-block"
              type="textarea"
              maxlength="1000"
              :placeholder="$t('modules.contract.email_notify')"
              rows="2"
            />
          </el-form-item>
          <el-form-item
            :label="$t('modules.contract.remark')"
            style="margin-bottom: 20px"
          >
            <el-input
              v-model="contractData.remark"
              maxlength="500"
              type="textarea"
              rows="2"
            />
          </el-form-item>
          <!-- 合同模块部分 -->
          <div style="font-size: 18px; margin: 0px 0px 20px 10px">
            <span
              style="
                display: inline-block;
                height: 30px;
                border-left: 4px solid #2569c3;
                text-indent: 10px;
              "
              >{{ $t("modules.contract.modules_title") }}</span
            >
            <el-button
              v-permission="{ permission: '10401000.MANAGE' }"
              class="w-8 ml-4"
              type="primary"
              @click="openAddModule"
              ><svg-icon icon-class="plus"
            /></el-button>
          </div>
          <template>
            <el-table
              :key="Math.random()"
              :data="moduleData"
              style="width: 100%; margin-left: 0px"
            >
              <template #empty>
                <el-empty :image-size="100" description="No data" />
              </template>
              <!--              <el-table-column-->
              <!--                prop="platCode"-->
              <!--                :label="$t('modules.contract.plat')"-->
              <!--              >-->
              <!--                <template v-slot="scope">-->
              <!--                  <span>{{ $t('contract_plat.' + scope.row.platCode) }}</span>-->
              <!--                </template>-->
              <!--              </el-table-column>-->
              <el-table-column
                prop="billingServiceCode"
                :label="$t('modules.contract.billing_method')"
                :formatter="formatterStatistic"
                width="220px"
              >
                <template v-slot="scope">
                  <p>{{ $t("contract_plat." + scope.row.platCode) }}</p>
                  <p>
                    {{
                      $t(
                        "flycare.billing_service." +
                          scope.row.billingServiceCode +
                          ".name"
                      )
                    }}
                  </p>
                </template>
              </el-table-column>
              <el-table-column :label="'Billing mode'" align="center">
                <template v-slot="scope">
                  <p v-if="scope.row.serviceAmount">
                    {{
                      "$" +
                      Number(scope.row.serviceAmount).toLocaleString() +
                      (scope.row.serviceQuantity
                        ? " for " +
                          Number(scope.row.serviceQuantity).toLocaleString() +
                          " " +
                          $t(
                            "flycare.billing_service." +
                              scope.row.billingServiceCode +
                              ".quantity_unit"
                          )
                        : "")
                    }}
                  </p>
                  <p v-if="scope.row.price">
                    {{
                      Number(scope.row.price).toLocaleString() +
                      " " +
                      $t(
                        "flycare.billing_service." +
                          scope.row.billingServiceCode +
                          ".price_unit"
                      )
                    }}
                  </p>
                  <p v-if="scope.row.freeNum">
                    {{
                      Number(scope.row.freeNum).toLocaleString() +
                      " " +
                      $t(
                        "flycare.billing_service." +
                          scope.row.billingServiceCode +
                          ".quantity_unit"
                      ) +
                      " for free " +
                      (scope.row.freeExpireTime
                        ? "(Expire: " + formatToMonth(scope.row.freeExpireTime) + ")"
                        : "")
                    }}
                  </p>
                </template>
              </el-table-column>
              <!--              <el-table-column-->
              <!--                :label="$t('modules.contract.service_quantity')"-->
              <!--                align="center"-->
              <!--              >-->
              <!--                <template v-slot="scope">-->
              <!--                  <span>{{ scope.row.serviceQuantity ? Number(scope.row.serviceQuantity).toLocaleString() : '-' }}</span>-->
              <!--                </template>-->
              <!--              </el-table-column>-->
              <el-table-column
                :label="$t('modules.contract.valid_period')"
                align="center"
              >
                <template v-slot="scope">
                  <span>{{
                    formatServiceValidTime(
                      scope.row.serviceStartTime,
                      scope.row.serviceEndTime,
                      scope.row.serviceQuantityUnit
                    )
                  }}</span>
                </template>
              </el-table-column>
              <!--              <el-table-column-->
              <!--                :label="$t('modules.contract.service_expire_time')"-->
              <!--                align="center"-->
              <!--              >-->
              <!--                <template v-slot="scope">-->
              <!--                  <span>{{ scope.row.serviceEndTime ? formatToMonth(parseInt(scope.row.serviceEndTime)):'-' }}</span>-->
              <!--                </template>-->
              <!--              </el-table-column>-->
              <!--              <el-table-column-->
              <!--                :label="$t('modules.contract.unit_price')"-->
              <!--                align="center"-->
              <!--              >-->
              <!--                <template v-slot="scope">-->
              <!--                  <el-tooltip-->
              <!--                    v-if="scope.row.price"-->
              <!--                    class="item"-->
              <!--                    effect="dark"-->
              <!--                    :content="scope.row.price + ' '-->
              <!--                      + $t('flycare.billing_service.' + scope.row.billingServiceCode + '.price_unit')"-->
              <!--                    placement="top-start">-->
              <!--                    <span>{{ '$' + Number(scope.row.price).toLocaleString() }}</span>-->
              <!--                  </el-tooltip>-->
              <!--                  <span v-else>{{ '-' }}</span>-->
              <!--                </template>-->
              <!--              </el-table-column>-->
              <!--              <el-table-column-->
              <!--                prop="freeNum"-->
              <!--                :label="$t('modules.contract.free_count')"-->
              <!--                align="center"-->
              <!--              >-->
              <!--                <template v-slot="scope">-->
              <!--                  <p>{{ scope.row.freeNum ? Number(scope.row.freeNum).toLocaleString() : '-' }}</p>-->
              <!--                  <p v-if="scope.row.freeExpireTime">-->
              <!--                    <el-tag size="small" type="warning">{{ 'Expire:' + formatToMonth(scope.row.freeExpireTime) }}</el-tag>-->
              <!--                  </p>-->
              <!--                </template>-->
              <!--              </el-table-column>-->

              <el-table-column
                prop="remark"
                :label="$t('common.remark')"
                align="center"
              />
              <el-table-column
                fixed="right"
                :label="$t('modules.contract.operate')"
                align="center"
              >
                <template v-slot="scope">
                  <el-button
                    v-permission="{ permission: '10401000.DELETE' }"
                    text
                    class="w-8"
                    size="small"
                    @click="DeleteModule(scope.$index, moduleData)"
                    >{{ $t("common.delete") }}</el-button
                  >
                  <el-button
                    v-permission="{ permission: '10401000.MANAGE' }"
                    text
                    class="w-8"
                    size="small"
                    @click="openContractModuleEdit(scope.$index, scope.row)"
                  >
                    {{ $t("modules.contract.contract_edit") }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
          <el-form-item class="buttomItem">
            <el-button text @click="back">{{ $t("common.cancel") }}</el-button>
            <el-button
              v-permission="{ permission: '10401000.MANAGE' }"
              :loading="btnLoading"
              type="primary"
              style="margin-right: 10px"
              @click="addContract"
              >{{ $t("common.confirm") }}</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <add-contract-module
      ref="addContractModule"
      v-model="addContractModuleVisible"
      @addModule="addModule"
      @editModule="editModuleInfo"
    />
    <contract-conflict ref="contractConflict" v-model="contractConflictVisible" />
    <customer-list
      ref="customerList"
      v-model="customerListVisible"
      @confirmSelect="confirmSelectCustomer"
    />
  </div>
</template>

<script>
import { addContract, getDefaultEmail } from "@/api/contract";
import { toTenYMD } from "@/utils/index";
import AddContractModule from "@/views/service-management/contract/components/contract-module";
import ContractConflict from "@/views/service-management/contract/components/contract-conflict";
import CustomerList from "@/views/service-management/components/customer-list";
import { checkUser } from "@/api/user";

export default {
  components: {
    AddContractModule,
    ContractConflict,
    CustomerList,
  },
  data() {
    var contractNumValidator = (rule, value, callback) => {
      if (!this.noContract && !value) {
        callback(new Error(this.$t("modules.contract.contract_number_require")));
      }
      callback();
    };
    var emailValidator = (rule, value, callback) => {
      // console.log(22222,value)
      var reg = new RegExp(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/);
      if (value !== "") {
        var emailList = value.split(";");
        for (var i = 0; i < emailList.length; i++) {
          if (emailList[i] !== "") {
            if (!reg.test(emailList[i])) {
              // console.log(222, emailList[i])
              return callback(new Error("邮箱格式有误"));
            }
          }
        }
        callback();
      }
      callback();
    };
    // var contractDateValidator = (rule, value, callback) => {
    //   console.log(3333, value)
    //   if (value.length > 0) {
    //     var startTime = value[value.length - 1]
    //     var currentTime = toStandardYMD(new Date().getTime())
    //     console.log('endTime', endTime)
    //     console.log('currentTime', currentTime)
    //     if (endTime < currentTime) {
    //       return callback(new Error('合同截止时间不能早于当前时间'))
    //     }
    //     callback()
    //   }
    //   callback()
    // }
    return {
      settings: {
        conditions: [],
        columns: [],
      },
      fullLoading: false,
      btnLoading: false,
      fixedEmail: "",
      radio: "",
      userName: "",
      userNameLabel: "",
      keyId: "",
      contractDate: [],
      moduleDate: [],
      laterPay: "1",
      prePay: "2",
      customerListVisible: false,
      contractConflictVisible: false,
      addContractModuleVisible: false,
      activeName: "first",
      moduleData: [],
      currentEditIndex: null,
      noContract: false,
      contractData: {
        userName: "",
        characterCode: "",
        keyId: "",
        contractNum: "",
        effectiveDate: "",
        expiringDate: "",
        signEntityId: "",
        remark: "",
        email: "",
        moduleList: [],
        noContract: 0,
      },

      moduleOptions: [],
      cycleOptions: [
        {
          value: "30",
          label: "Month",
        },
      ],
      fakeInfor: [],
      userNameForm: {
        characterCode: "",
        keyId: "",
      },
      keyIdOption: [
        {
          value: "",
          label: "",
        },
      ],
      customerData: [],
      customerDetail: "",
      signOptions: [
        { label: "新大陆支付NLPM01", value: "NLPM01" },
        { label: "新大陆香港NLHK01", value: "NLHK01" },
        { label: "新大陆巴西NLBR03", value: "NLBR03" },
      ],
      rules: {
        userName: [
          {
            required: true,
            message: this.$t("modules.contract.select_customer_name"),
            trigger: "change",
          },
        ],
        email: [
          {
            validator: emailValidator,
            message: this.$t("modules.login.message.invalid_email_format"),
          },
        ],
        contractNum: [
          {
            validator: contractNumValidator,
            message: this.$t("modules.contract.contract_number_require"),
            trigger: "blur",
          },
        ],
        effectiveDate: [
          {
            required: true,
            message: this.$t("modules.contract.contract_date_require"),
            trigger: "blur",
          },
        ],
        signEntityId: [
          {
            required: true,
            message: this.$t("modules.contract.sign_require"),
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    settingList() {
      return {
        columns: [
          {
            title: this.$t("common.short_name"),
            code: "SHORT_NAME",
          },
          {
            title: this.$t("common.address"),
            code: "ADDRESS",
          },
          {
            title: this.$t("common.link_man"),
            code: "LINKMAN",
          },
          {
            title: this.$t("common.mobile"),
            code: "MOBILE",
          },
          {
            title: this.$t("common.email"),
            code: "EMAIL",
          },
        ],
      };
    },
    defaultSettings() {
      return {
        columns: [],
      };
    },
  },
  mounted() {
    // 获取当前用户信息
    // const userInfo = JSON.parse(
    //   localStorage.getItem(this.$store.getters.keys.storage.username)
    // )
    // this.keyIdOption = this.loadAll()
    this.getDefaultNotifyEmail();
  },
  methods: {
    showHeader(label) {
      // 重置高度
      var list = this.settings["columns"];
      return list ? list.includes(label) : false;
    },
    showFormItem(label) {
      var list = this.settings["conditions"];
      return list ? list.includes(label) : false;
    },
    // 返回
    back() {
      this.$router.back();
    },
    formatToMonth(timestamp) {
      return toTenYMD(timestamp);
    },
    changeNoContract(val) {
      if (val) {
        this.contractData.contractNum = "";
        this.$refs["contractData"].validateField("contractNum");
      }
    },
    getDefaultNotifyEmail() {
      getDefaultEmail().then((res) => {
        this.fixedEmail = "";
        if (res.length > 0) {
          res.forEach((email) => {
            this.fixedEmail += email + ";";
          });
          this.fixedEmail = this.fixedEmail.substring(0, this.fixedEmail.length - 1);
        }
      });
    },
    // 打开合同模块对话框
    openContractModuleEdit(index, moduleInfo) {
      this.addContractModuleVisible = true;
      this.currentEditIndex = index;
      this.$nextTick(() => {
        this.$refs.addContractModule.openDialog({ ...moduleInfo }, true);
      });
    },
    editModuleInfo(moduleInfo) {
      console.log(moduleInfo);
      console.log(this.currentEditIndex);
      this.moduleData[this.currentEditIndex] = moduleInfo;
      console.log(this.moduleData);
      this.addContractModuleVisible = false;
      this.currentEditIndex = null;
    },
    formatServiceValidTime(serviceStartTime, serviceEndTime, serviceQuantityUnit) {
      if (!serviceStartTime && !serviceEndMonth) return "-";
      let serviceStartMonth = "*";
      let serviceEndMonth = "*";
      if (serviceStartTime) {
        serviceStartMonth = this.formatToMonth(serviceStartTime);
        if (serviceQuantityUnit === "SINGLE") {
          return serviceStartMonth;
        }
      }
      if (serviceEndTime) {
        serviceEndMonth = this.formatToMonth(serviceEndTime);
      }
      return serviceStartMonth + " ~ " + serviceEndMonth;
    },
    openAddModule() {
      this.addContractModuleVisible = true;
      this.$nextTick(() => {
        this.$refs.addContractModule.openDialog();
      });
    },
    openContractConflict(addContractResult) {
      this.contractConflictVisible = true;
      this.$nextTick(() => {
        this.$refs.contractConflict.openDialog(addContractResult);
      });
    },
    addModule(moduleInfo) {
      // console.log(moduleInfo)
      if (moduleInfo) {
        this.moduleData.push(JSON.parse(JSON.stringify(moduleInfo)));
      }
    },
    // 点击查看合同模块详情
    handleClick(row) {
      console.log(row);
    },
    // 删除合同模块
    DeleteModule(index, rows) {
      // 加个确认
      this.$confirm(this.$t("tip_content.delete_module"), "", {
        confirmButtonText: this.$t("common.confirm"),
        cancelButtonText: this.$t("common.cancel"),
        type: "warning",
      })
        .then(() => {
          rows.splice(index, 1);
        })
        .catch((e) => {});
    },
    openCustomerList() {
      this.customerListVisible = true;
      this.$nextTick(() => {
        this.$refs.customerList.openDialog();
      });
    },
    // 增加合同
    addContract() {
      // console.log('test')
      console.log(this.contractData);
      this.$refs["contractData"].validate((valid) => {
        if (valid) {
          // this.contractData.effectiveDate =
          //   this.contractData.contractDate[0].toString()
          // this.contractData.expiringDate =
          //   this.contractData.contractDate[1].toString()
          this.contractData.noContract = this.noContract ? 1 : 0;
          this.contractData["moduleList"] = this.moduleData;
          this.btnLoading = true;
          this.fullLoading = true;
          addContract(this.contractData)
            .then((res) => {
              if (res && res.length > 0) {
                this.openContractConflict(res);
              } else {
                this.$message.success(this.$t("common.success"));
                this.$router.back();
              }
              this.btnLoading = false;
              this.fullLoading = false;
            })
            .catch((err) => {
              this.$message.error(err.message);
            })
            .finally(() => {
              this.btnLoading = false;
              this.fullLoading = false;
            });
        }
      });
    },
    // 处理用户姓名的分页
    handleNameCurrentChange(val) {
      this.namePageNo = val;
      this.getKeyId();
    },
    // 确定获取的UserName
    confirmSelectCustomer(detail) {
      checkUser(detail.keyId).then((res) => {
        if (res.bindOaId) {
          this.contractData.characterCode = "OPERATOR";
          this.contractData.keyId = detail.keyId;
          this.contractData.userName = detail.name;
        } else {
          this.$message.warning(this.$t("customer.oa_customer_bind_tip"));
        }
      });
    },
    // 取消获取的UserName
    cancelUserName() {
      // this.userNameForm.characterCode = this.userNameForm.keyId = ''
      this.getUserNameVisible = false;
      this.radio = "";
    },
    clearAllModule() {
      this.moduleForm.statisticMethodCode = "";
      this.statisticOptions.length = 0;
    },
    // 获取statisticCode对应的name
    formatterStatistic(row, column, cellValue) {
      const obj = this.statisticOptions.find((item) => item.value === cellValue);
      if (obj) {
        return obj.label;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.box {
  margin: 0.2em 0.5em;
}
.title-logo {
  font-size: 0.8em;
  margin-left: 0px;
  color: #909399;
}
.box-header {
  font-weight: bold;
  font-size: 1.8em;
  color: #12263f;
}
.buttomItem {
  margin-top: 40px;
  float: right;
}
.theFirst {
  margin: 10px 6px;
  width: 500px;
}
.textLayout {
  display: flex;
  justify-content: center;
  align-items: center;
}
.flexContract {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.addModuleFlex {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.item {
  margin-bottom: 20px;
  margin-right: 30px;
}
</style>
